package com.working.libcommon.adapter

import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import androidx.core.util.containsValue
import androidx.recyclerview.widget.RecyclerView
import com.working.libcommon.exts.cast
import com.working.libcommon.exts.doWithTry

internal class DecorateAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    val views: SparseArray<View> = SparseArray()
    var index = 100000
    fun add(view: View) {
        if (!views.containsValue(view)) {
            index++
            views.put(index, view)
            notifyItemInserted(views.indexOfValue(view))
        }
    }

    fun clear() {
        views.clear()
        notifyDataSetChanged()
    }

    fun remove(view: View) {
        val index = views.indexOfValue(view)
        if (index != -1) {
            views.removeAt(index)
            notifyItemRemoved(index)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = doWithTry {
        val parent1 = views[viewType].parent
        parent1?.cast<ViewGroup>()?.removeView(views[viewType])
        object : RecyclerView.ViewHolder(views[viewType]) {}
    }

    override fun getItemCount() = views.size()

    override fun getItemViewType(position: Int) = views.keyAt(position)

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    }
}
